﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Configuration;
using BLL;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;
using Model;
using System.Threading;

namespace Sales
{
    public partial class ProgressForm : Form
    {
        string url = ConfigurationSettings.AppSettings["WebService"].ToString();
        private BasicBLL cpdaHBLL;

        delegate void MyDele();

        public delegate void MyDelegate();//声明一个委托 

        public Thread oThread;

        public ProgressForm()
        {
            InitializeComponent();
        }

        private void ProgressForm_Load(object sender, EventArgs e)
        {
            this.FormBorderStyle = FormBorderStyle.None;
            this.timer1.Start();
            this.timer1.Interval = 10000;//设置显示的时间（单位毫秒） 
            this.DesktopLocation = new Point(150, 150);//设置这个窗体加载时出现的位置 
            this.osProgress1.AutoProgress = true;
            this.label1.Text = "正在从服务器端下载数据请稍候。。";

              oThread = new Thread(new System.Threading.ThreadStart(Execution));
            oThread.Start();
            while (!oThread.IsAlive)
            {
                this.Close();
            }
        }
        private void Execution()
        {
            System.Threading.Thread.Sleep(2000);//线程休眠2秒 
            this.label1.BeginInvoke(new MyDelegate(DownloadGetYyyH));
        }
        private void DownloadGetYyyH()
        {
            ArrayList parms = new ArrayList();
            cpdaHBLL = new BasicBLL();
            string reslut = "";


            parms.Add("");
            reslut = DSWebService.InvokeWebService(url, "GetYyyData", parms.ToArray());

            if (reslut != "-2")
            {

                if (reslut != "")
                {
                    DataTable dt = DeserializeDataTable(reslut);

                    //插入数据库
                    foreach (DataRow newdr in dt.Rows)
                    {
                        string ygbh = newdr["ygbh"].ToString();
                        yyydaHModel model = cpdaHBLL.GetyyydaHModel(newdr);
                        if (cpdaHBLL.IsExistYyy(ygbh))
                        {
                            bool s1 = cpdaHBLL.Updatejbxx_yyydaHModel(model);
                        }
                        else
                        {
                            bool s2 = cpdaHBLL.Addjbxx_yyydaHModel(model);
                        }
                    }
                    this.label1.Text = "营业员信息 下载完成！";
                    oThread.Abort();
                }
                else
                {

                    this.label1.Text = "营业员信息 无数据下载！";
                    oThread.Abort();
                }
            }
            else
            {
                MessageBox.Show("无法连接目标服务器请检查网络！提取营业员信息失败！");

            }
        }



        /// 将二进制文件反序列化后转化为DataSet

        public DataSet GetDatasetFromByte(byte[] ZipByte)
        {
            byte[] buffer = Decompress(ZipByte);
            BinaryFormatter ser = new BinaryFormatter();
            DataSetSurrogate dss;
            dss = (DataSetSurrogate)ser.Deserialize(new MemoryStream(buffer));
            DataSet DS = dss.ConvertToDataSet();
            return DS;

        }


        /// <summary>
        /// 反序列化DataTable
        /// </summary>
        /// <param name="pXml">序列化的DataTable</param>
        /// <returns>DataTable</returns>
        public static DataTable DeserializeDataTable(string pXml)
        {

            StringReader strReader = new StringReader(pXml);
            XmlReader xmlReader = XmlReader.Create(strReader);
            XmlSerializer serializer = new XmlSerializer(typeof(DataTable));

            DataTable dt = serializer.Deserialize(xmlReader) as DataTable;
            return dt;
        }
        ///将压缩后的二进制数组解压

        public static byte[] Decompress(byte[] data)
        {      ///data参数为压缩后的二进制数组
            try
            {
                MemoryStream ms = new MemoryStream(data);
                Stream zipStream = null;
                zipStream = new GZipStream(ms, CompressionMode.Decompress);
                byte[] dc_data = null;
                dc_data = EtractBytesFormStream(zipStream, data.Length);
                return dc_data;

                ///返回解压后的二进制数组
            }
            catch
            {
                return null;
            }
        }
        public static byte[] EtractBytesFormStream(Stream zipStream, int dataBlock)
        {
            try
            {
                byte[] data = null;
                int totalBytesRead = 0;
                while (true)
                {
                    Array.Resize(ref data, totalBytesRead + dataBlock + 1);
                    int bytesRead = zipStream.Read(data, totalBytesRead, dataBlock);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    totalBytesRead += bytesRead;
                }
                Array.Resize(ref data, totalBytesRead);
                return data;
            }
            catch
            {
                return null;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
